#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice, IceGrid
import os, sys, datetime, math, thread

try:
    HOME = os.environ['FIPA']
except KeyError:
    print 'FIPA environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE = os.path.join(HOME, 'test', 'Spammer.ice')
SRC = os.path.join(HOME, 'src', 'python')
sys.path.append(SRC)
Ice.loadSlice('--all -I/usr/share/Ice/slice', ['-I' + SLICE, FILE])

import FIPA
import Test
import AgentI
from AgentI import *

class AMI_Model_beginTestI (object):

    def ice_response (self):
        pass

    def ice_exception (self, ex):
        print 'SnifferI: ' + str(ex)

class SnifferI (Test.Sniffer):
    
    def __init__ (self, comm):
        self.__mts = False
        self.__messages = 0
        self.__messageSizeInBytes = 200
        self.clean()

    def setConfiguration (self, mts, messages, messageSizeInBytes, curr = None):
        self.__mts = mts
        self.__messages = messages
        self.__messageSizeInBytes = messageSizeInBytes

    def beginTest (self, agentType, curr):

        if self.__numberOfPairs == -1:
            query = IceGrid.QueryPrx.checkedCast(curr.adapter.getCommunicator().stringToProxy('FIPA/Query'))
            df = FIPA.DFPrx.checkedCast(query.findObjectById(curr.adapter.getCommunicator().stringToIdentity('DF')))
            self.__numberOfPairs = len(df.search(FIPA.DfAgentDescription(None, [FIPA.ServiceDescription('spammer')])))

        if agentType == 'spammer' and self.__spammers == -1:
            self.__spammers += 1
            self.__spammerBeginningTime = datetime.datetime.today()

        if agentType == 'user' and self.__users == -1:
            self.__users += 1
            self.__userBeginningTime = datetime.datetime.today()

    def endTest (self, agentType, curr):

        if agentType == 'spammer':
            self.__spammers += 1            
            if self.__numberOfPairs == self.__spammers:
                self.__spammerEndTime = datetime.datetime.today()
        elif agentType == 'user':
            self.__users += 1
            if self.__numberOfPairs == self.__users / self.__numberOfPairs:
                self.__userEndTime = datetime.datetime.today()
                self.createLog(self.__numberOfPairs)      
                self.clean()          

    def createLog (self, pairs):
        aux = 'NoMTS'
        if self.__mts:
            aux = 'MTS'
        file = str(pairs) + 'x' + str(self.__messages) + 'x' + str(self.__messageSizeInBytes) + 'x' + aux
        filepath = os.path.join(HOME, 'logs', file)
        f = open(filepath, 'a')
        f.write('Number of spammers: ' + str(self.__numberOfPairs) + '.\n')
        f.write('Number of users: ' + str(self.__numberOfPairs) + '.\n')
        f.write('Number of messages per spammer: ' + str(self.__messages) +'.\n' )
        nMessages = self.__numberOfPairs * self.__numberOfPairs * self.__messages
        f.write('Total number of messages proccessed: ' + str(nMessages) +'.\n' )
        nKBytes = self.__messageSizeInBytes * nMessages / 1024
        f.write('Message size (in bytes): ' + str(self.__messageSizeInBytes) + '.\n' )
        f.write('Total number of KB proccessed: ' + str(nKBytes) +'.\n' )
        f.write('Was the MTS used?: ' + str(self.__mts) + '.\n')
        f.write('Spamming time: ' + str(self.__spammerEndTime - self.__spammerBeginningTime) + '.\n')
        f.write('Processing time: ' + str(self.__userEndTime - self.__userBeginningTime) + '.\n')
        f.close()

    def clean (self):
        self.__spammerBeginnningTime = None
        self.__spammerEndTime = None
        self.__userBeginnningTime = None
        self.__userEndTime = None

        self.__spammers = -1
        self.__users = -1
        self.__numberOfPairs = -1

class Server (Ice.Application):

    def run (self, argv):
        self.shutdownOnInterrupt()
        adapter = self.communicator().createObjectAdapter('SnifferAdapter')
        adapter.activate()

        adapter.add(SnifferI(self.communicator()),
                    self.communicator().stringToIdentity('Sniffer'))
        self.communicator().waitForShutdown()

        return 0
            
Server().main(sys.argv)
